package com.lemon.stock.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lemon.stock.app.StockApplication
import com.lemon.stock.entity.Batch
import com.lemon.stock.entity.Stock
import com.lemon.stock.entity.Trade
import com.lemon.stock.util.*
import kotlinx.coroutines.launch
import java.util.*

class TradeViewModel: ViewModel() {
    private val _trades = MutableLiveData<List<Trade>>()
    private val _finished = MutableLiveData<Boolean>()

    val trades: LiveData<List<Trade>>
        get() = _trades
    val finished: LiveData<Boolean>
        get() = _finished

    fun getTrades(stockId: String, index: Int){
        viewModelScope.launch {
            val tradeDao = StockApplication.getDataRoom().tradeDao()
            val liTrades = tradeDao.stockTrades(stockId, index)
            _trades.postValue(liTrades)
        }
    }

    fun finishReset(){
        _finished.postValue(false)
    }

    /**
     * 预估红利税
     * 红利逻辑并不严谨，此处只考虑了一次分红的情况，未考虑两次分红在1年以内的情况
     * @param stock 股票类
     * @param amount 卖出数量
     * @param date 卖出日期
     *
     */
    fun bonusTax(stock: Stock, amount: Int, date: Calendar): Float {
        return sysPredictBonusTax(stock, amount, date.timeInMillis)
    }

    /**
     * 证券买入
     * @param stock 股票类
     * @param price 买入单价
     * @param amount 买入数量
     * @param date 买入日期
     * @param commission 手续费
     * @param transfer 过户费
     *
     */
    fun tradeBuy(stock: Stock, price: Float, amount: Int, date: Calendar, commission: Float, transfer: Float){
        val tradeDao = StockApplication.getDataRoom().tradeDao()
        val stockDao = StockApplication.getDataRoom().stockDao()
        var trade = sysStockBuy(stock,price, amount, date.timeInMillis,commission, transfer)

        tradeDao.insert(trade)
        sysStockGather(stock)
        stockDao.update(stock)

        _finished.postValue(true)
    }

    /**
     * 证券卖出
     * @param tradeDao 购买记录的数据库访问类
     * @param stock 股票类
     * @param price 卖出单价
     * @param amount 卖出数量
     * @param date 卖出日期
     * @param commission 手续费
     * @param transfer 过户费
     * @param tax 印花税
     *
     */
    fun tradeSell(stock: Stock, price: Float, amount: Int, date: Calendar, commission: Float, transfer: Float, tax: Float, btax: Float){
        val tradeDao = StockApplication.getDataRoom().tradeDao()
        val stockDao = StockApplication.getDataRoom().stockDao()
        val batchDao = StockApplication.getDataRoom().batchDao()
        val bonusDao = StockApplication.getDataRoom().bonusDao()

        val pairs = sysStockSell(tradeDao, stock, price, amount, date.timeInMillis, commission, transfer, tax)
        var split = pairs.first
        var saveTrade = pairs.second
        stock.bonusTax += btax

        var saveBonus = sysBonusTax(bonusDao, saveTrade)
        var batch: Batch? = null

        for(trade in saveTrade){
            tradeDao.update(trade)
        }
        if(split !=null){
            tradeDao.insert(split)
        }
        sysStockGather(stock)

        for(bonus in saveBonus){
            bonusDao.update(bonus)
        }
        if(stock.holdStock == 0){
            batch = sysStockBatch(stock, date.timeInMillis)
        }

        if(batch !=null){
            batchDao.insert(batch)
            tradeDao.endBatch(stock.stockId, stock.investIndex)
        }
        stock.bonusTax += btax
        stockDao.update(stock)
        _finished.postValue(true)
    }

    fun deleteTrade(stock: Stock, id: Long){
        val stockDao = StockApplication.getDataRoom().stockDao()
        val tradeDao = StockApplication.getDataRoom().tradeDao()
        var trade = tradeDao.entity(id)
        trade.status = 4

        tradeDao.update(trade)
        sysStockGather(stock)
        stockDao.update(stock)
    }

    fun clearTrade(stock: Stock){
        val stockDao = StockApplication.getDataRoom().stockDao()
        val tradeDao = StockApplication.getDataRoom().tradeDao()
        sysStockGather(stock)
        stockDao.update(stock)
    }

    /**
     * 股票分红
     * @param stock 股票类
     * @param date 除权日期，时间戳（毫秒）
     * @param money 每10股分红金额
     * @param amount 每10股分股数量
     *
     */
    fun stockBonus(stock: Stock, money: Float, amount: Int, date: Calendar){
        val stockDao = StockApplication.getDataRoom().stockDao()
        val tradeDao = StockApplication.getDataRoom().tradeDao()
        val bonusDao = StockApplication.getDataRoom().bonusDao()

        val triple = sysStockBonus(tradeDao, stock, date.timeInMillis, money/10, amount.toFloat()/10, stock.holdStock)
        var bonus = triple.first
        var liTrade = triple.second
        var bonusTrade = triple.third

        bonusDao.insert(bonus)

        for(trade in liTrade){
            trade.bonusId = bonus.id
            tradeDao.update(trade)
        }
        if(bonusTrade !=null){
            tradeDao.insert(bonusTrade)
        }
        stockDao.update(stock)
        _finished.postValue(true)
    }
}